package com.lxw.report.meta.excel.handler;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext;
import com.lxw.report.meta.excel.annotation.DropDownData;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.lang.reflect.Field;

/**
 * @author lxw
 * @time 2022/3/30 15:37
 */
public class LocalSheetWriteHandler implements SheetWriteHandler {

    private Class classZ;

    public LocalSheetWriteHandler(Class classZ){
        this.classZ = classZ;
    }

    @Override
    public void afterSheetCreate(SheetWriteHandlerContext context) {
        DataValidationHelper helper = context.getWriteSheetHolder().getSheet().getDataValidationHelper();

        //创建文本格式
        Workbook workBook=context.getWriteWorkbookHolder().getWorkbook();
        CellStyle style= workBook.createCellStyle();
        DataFormat format = workBook.createDataFormat();
        style.setDataFormat(format.getFormat("@"));

        //读取注解信息
        Field[] fields = this.classZ.getDeclaredFields();
        // 循环判断哪些字段有下拉数据集，并获取
        for(int i =0;i<fields.length;i++){
            //设置文本格式
            context.getWriteSheetHolder().getSheet().setDefaultColumnStyle(i, style);

            // 解析注解信息
            Field field = fields[i];
            DropDownData dropDownData = field.getAnnotation(DropDownData.class);
            if(null != dropDownData){
                // 获取固定下拉信息
                String[] source = dropDownData.value();
                if(null != source && source.length > 0){
                    // 下拉列表约束数据
                    DataValidationConstraint constraint = helper.createExplicitListConstraint(source);
                    // 设置下拉单元格的首行 末行 首列 末列
                    CellRangeAddressList rangeList = new CellRangeAddressList(1, 65536, i, i);
                    // 设置约束
                    DataValidation validation = helper.createValidation(constraint, rangeList);
                    // 阻止输入非下拉选项的值
                    validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
                    validation.setShowErrorBox(true);
                    validation.setSuppressDropDownArrow(true);
                    validation.createErrorBox("提示","请选择下拉数据");
                    // validation.createPromptBox("填写说明：","填写内容只能为下拉数据集中的单位，其他单位将会导致无法入仓");
                    context.getWriteSheetHolder().getSheet().addValidationData(validation);
                }
            }
        }
    }
}
